﻿using MouthAnimationFrame;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;

// A behaviour that is attached to a playable
public class MouthAnimationBehaviour : PlayableBehaviour
{

    public string mouthEventName;
    public Animator animatorRef;
    private bool isInPlay = false;

    // Called when the owning graph starts playing
    public override void OnGraphStart(Playable playable)
    {
        isInPlay = false;
    }

    // Called when the owning graph stops playing
    public override void OnGraphStop(Playable playable)
    {
        isInPlay = false;
    }

    // Called when the state of the playable is set to Play
    public override void OnBehaviourPlay(Playable playable, FrameData info)
    {
        isInPlay = false;
    }

    // Called when the state of the playable is set to Paused
    public override void OnBehaviourPause(Playable playable, FrameData info)
    {
        animatorRef?.StopMouthAnimation();
        isInPlay = false;
    }

    public override void ProcessFrame(Playable playable, FrameData info, object playerData)
    {
        if (animatorRef == null)
        {
            animatorRef = playerData as Animator;
        }
        if (!isInPlay)
        {
            //BeginPlay在ProcessFrame之前,所以无法在beginPlay里通过trackAsset来直接获取animator(应该有弯路可以实现)
            isInPlay = true;
            //这点有一个问题需要解决,如果是完全匹配着走过去的话,没啥问题
            //但是如果是中间停止后重新播放,则可能导致口型不对
            //同样如果是全局暂停,这些就需要实现口型的Pause状态(暂未实现)
            animatorRef?.StartMouthAnimation(mouthEventName);
        }
    }
}
